package logic

import (
	"cart_srv/cart"
	"cart_srv/internal/svc"
	"cart_srv/model/mysql"
	"cart_srv/model/redis"
	"context"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cart.AddCartRequest) (*cart.AddCartResponse, error) {
	c := mysql.Cart{
		GoodsId: int(in.GoodsId),
		Name:    in.Name,
		Num:     int(in.Num),
		Price:   float64(in.Price),
		Select:  int(in.Select),
		Status:  int(in.Status),
	}
	err := c.AddCart()
	if err != nil {
		logx.Error("添加购物车失败:", err)
		return nil, err
	}
	if c.ID == 0 {
		logx.Error("商品不存在")
		return nil, err
	}
	cartMap := map[string]interface{}{
		"goods_id": c.GoodsId,
		"name":     c.Name,
		"num":      c.Num,
		"price":    c.Price,
		"select":   c.Select,
		"status":   c.Status,
	}
	err = redis.AddCart(cartMap)
	if err != nil {
		logx.Error("购物车添加缓存失败:", err)
		return nil, err
	}
	if c.Name == "" {
		logx.Error("商品为空", err)
		return nil, err
	}

	return &cart.AddCartResponse{
		CartId: int64(c.ID),
	}, nil
}
